import React, { useState, useEffect } from 'react';
import { invoke } from '@tauri-apps/api/core';
import {
  ComputerDesktopIcon,
  CpuChipIcon,
  CircleStackIcon,
  ServerIcon,
  InformationCircleIcon,
} from '@heroicons/react/24/outline';

interface AppInfo {
  name: string;
  version: string;
  tauri_version: string;
  identifier: string;
}

interface SystemInfo {
  platform: string;
  arch: string;
  version: string;
  hostname: string;
  uptime: number;
  total_memory: number;
  free_memory: number;
  cpu_count: number;
  load_average: number[];
}

interface ProcessInfo {
  pid: number;
  name: string;
  cpu_usage: number;
  memory_usage: number;
  start_time: number;
}

const SystemInfo: React.FC = () => {
  // const { t } = useTranslation();
  const [appInfo, setAppInfo] = useState<AppInfo | null>(null);
  const [systemInfo, setSystemInfo] = useState<SystemInfo | null>(null);
  const [processInfo, setProcessInfo] = useState<ProcessInfo | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const loadSystemData = async () => {
    try {
      setLoading(true);
      setError(null);

      const [appData, sysData, procData] = await Promise.all([
        invoke<AppInfo>('get_app_info'),
        invoke<SystemInfo>('get_system_info'),
        invoke<any>('get_process_info'),
      ]);

      setAppInfo(appData);
      setSystemInfo(sysData);
      setProcessInfo(procData);
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadSystemData();
  }, []);

  const formatBytes = (bytes: number) => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  const formatUptime = (seconds: number) => {
    const days = Math.floor(seconds / 86400);
    const hours = Math.floor((seconds % 86400) / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);

    if (days > 0) {
      return `${days}天 ${hours}小时 ${minutes}分钟`;
    } else if (hours > 0) {
      return `${hours}小时 ${minutes}分钟`;
    } else {
      return `${minutes}分钟`;
    }
  };

  if (loading) {
    return (
      <div className="flex h-64 items-center justify-center">
        <div className="h-8 w-8 animate-spin rounded-full border-b-2 border-blue-600"></div>
        <span className="ml-2">加载系统信息...</span>
      </div>
    );
  }

  if (error) {
    return (
      <div className="rounded-lg border border-red-200 bg-red-50 p-4 dark:border-red-800 dark:bg-red-900/20">
        <div className="flex items-center">
          <InformationCircleIcon className="mr-2 h-5 w-5 text-red-500" />
          <span className="text-red-700 dark:text-red-400">
            加载失败: {error}
          </span>
        </div>
        <button
          onClick={loadSystemData}
          className="mt-2 rounded bg-red-600 px-4 py-2 text-white hover:bg-red-700"
        >
          重试
        </button>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100">
          系统信息
        </h1>
        <button
          onClick={loadSystemData}
          className="flex items-center rounded bg-blue-600 px-4 py-2 text-white hover:bg-blue-700"
        >
          <ServerIcon className="mr-2 h-4 w-4" />
          刷新
        </button>
      </div>

      {/* 应用信息 */}
      {appInfo && (
        <div className="rounded-lg border border-gray-200 bg-white p-6 dark:border-gray-700 dark:bg-gray-800">
          <h2 className="mb-4 flex items-center text-lg font-semibold">
            <InformationCircleIcon className="mr-2 h-5 w-5 text-blue-500" />
            应用信息
          </h2>
          <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
            <div>
              <label className="text-sm text-gray-600 dark:text-gray-400">
                应用名称
              </label>
              <div className="font-medium">{appInfo.name}</div>
            </div>
            <div>
              <label className="text-sm text-gray-600 dark:text-gray-400">
                版本
              </label>
              <div className="font-medium">{appInfo.version}</div>
            </div>
            <div>
              <label className="text-sm text-gray-600 dark:text-gray-400">
                Tauri 版本
              </label>
              <div className="font-medium">{appInfo.tauri_version}</div>
            </div>
            <div>
              <label className="text-sm text-gray-600 dark:text-gray-400">
                标识符
              </label>
              <div className="text-xs font-medium">{appInfo.identifier}</div>
            </div>
          </div>
        </div>
      )}

      {/* 系统信息 */}
      {systemInfo && (
        <div className="rounded-lg border border-gray-200 bg-white p-6 dark:border-gray-700 dark:bg-gray-800">
          <h2 className="mb-4 flex items-center text-lg font-semibold">
            <ComputerDesktopIcon className="mr-2 h-5 w-5 text-green-500" />
            系统信息
          </h2>
          <div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
            <div>
              <label className="text-sm text-gray-600 dark:text-gray-400">
                操作系统
              </label>
              <div className="font-medium">{systemInfo.platform}</div>
            </div>
            <div>
              <label className="text-sm text-gray-600 dark:text-gray-400">
                架构
              </label>
              <div className="font-medium">{systemInfo.arch}</div>
            </div>
            <div>
              <label className="text-sm text-gray-600 dark:text-gray-400">
                版本
              </label>
              <div className="font-medium">{systemInfo.version}</div>
            </div>
            <div>
              <label className="text-sm text-gray-600 dark:text-gray-400">
                主机名
              </label>
              <div className="font-medium">{systemInfo.hostname}</div>
            </div>
            <div>
              <label className="text-sm text-gray-600 dark:text-gray-400">
                运行时间
              </label>
              <div className="font-medium">
                {formatUptime(systemInfo.uptime)}
              </div>
            </div>
            <div>
              <label className="text-sm text-gray-600 dark:text-gray-400">
                CPU 核心数
              </label>
              <div className="font-medium">{systemInfo.cpu_count}</div>
            </div>
          </div>
        </div>
      )}

      {/* 内存信息 */}
      {systemInfo && (
        <div className="rounded-lg border border-gray-200 bg-white p-6 dark:border-gray-700 dark:bg-gray-800">
          <h2 className="mb-4 flex items-center text-lg font-semibold">
            <CircleStackIcon className="mr-2 h-5 w-5 text-purple-500" />
            内存信息
          </h2>
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <span>总内存</span>
              <span className="font-medium">
                {formatBytes(systemInfo.total_memory)}
              </span>
            </div>
            <div className="flex items-center justify-between">
              <span>可用内存</span>
              <span className="font-medium">
                {formatBytes(systemInfo.free_memory)}
              </span>
            </div>
            <div className="flex items-center justify-between">
              <span>已用内存</span>
              <span className="font-medium">
                {formatBytes(systemInfo.total_memory - systemInfo.free_memory)}
              </span>
            </div>
            <div className="h-2 w-full rounded-full bg-gray-200 dark:bg-gray-700">
              <div
                className="h-2 rounded-full bg-purple-600"
                style={{
                  width: `${((systemInfo.total_memory - systemInfo.free_memory) / systemInfo.total_memory) * 100}%`,
                }}
              ></div>
            </div>
            <div className="text-sm text-gray-600 dark:text-gray-400">
              使用率:{' '}
              {(
                ((systemInfo.total_memory - systemInfo.free_memory) /
                  systemInfo.total_memory) *
                100
              ).toFixed(1)}
              %
            </div>
          </div>
        </div>
      )}

      {/* 进程信息 */}
      {processInfo && (
        <div className="rounded-lg border border-gray-200 bg-white p-6 dark:border-gray-700 dark:bg-gray-800">
          <h2 className="mb-4 flex items-center text-lg font-semibold">
            <CpuChipIcon className="mr-2 h-5 w-5 text-orange-500" />
            当前进程
          </h2>
          <div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-4">
            <div>
              <label className="text-sm text-gray-600 dark:text-gray-400">
                进程 ID
              </label>
              <div className="font-medium">{processInfo.pid}</div>
            </div>
            <div>
              <label className="text-sm text-gray-600 dark:text-gray-400">
                进程名
              </label>
              <div className="font-medium">{processInfo.name}</div>
            </div>
            <div>
              <label className="text-sm text-gray-600 dark:text-gray-400">
                CPU 使用率
              </label>
              <div className="font-medium">
                {processInfo.cpu_usage?.toFixed(1) || '0.0'}%
              </div>
            </div>
            <div>
              <label className="text-sm text-gray-600 dark:text-gray-400">
                内存使用
              </label>
              <div className="font-medium">
                {formatBytes(processInfo.memory_usage || 0)}
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default SystemInfo;
